package bootstrap

import (
	"context"
	"net/http"
	"time"

	"github.com/cy18cn/dapr-demo/g"
	"github.com/cy18cn/dapr-demo/g/handlers"
	"github.com/cy18cn/dapr-demo/service"
	"github.com/julienschmidt/httprouter"
)

var (
	srv *http.Server
)

func StartDaprTestApi(addr string) (err error) {
	router := httprouter.New()
	router.GET("/dapr/state/save", service.Save)
	router.GET("/dapr/state/get", service.Get)

	srv = &http.Server{
		Addr:    addr,
		Handler: handlers.ParseFormHandler(g.GetLogger(), router),
	}

	return srv.ListenAndServe()
}

func StopServer() error {
	if srv != nil {
		ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
		defer cancel()
		return srv.Shutdown(ctx)
	}

	return nil
}
